package com.bootlever.framework.core.web.freemarker;

import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import java.io.IOException;


@Configuration
public class FreeMarkerMvcConfiguration extends WebMvcConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(FreeMarkerMvcConfiguration.class);

    @Autowired
    private FreeMarkerViewResolver freeMarkerViewResolver;

    @Bean
    public FreeMarkerViewResolver freeMakerViewResolver() {
        logger.info("初始化FreeMarkerResolver");
        if (freeMarkerViewResolver != null) {
            logger.info("FreeMarkerResolver设置优先级为5");
            freeMarkerViewResolver.setOrder(5);
        }
        return freeMarkerViewResolver;
    }

    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() throws IOException, TemplateException {
        logger.info("初始化FreeMakerConfigurer");
        FreeMarkerConfigurationFactory freeMarkerConfigurationFactory = new FreeMarkerConfigurationFactory();
        freeMarkerConfigurationFactory.setTemplateLoaderPath("classpath:templates");
        freeMarkerConfigurationFactory.setDefaultEncoding("UTF-8");
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setConfiguration(freeMarkerConfigurationFactory.createConfiguration());
        return configurer;
    }


}
